import os
import re
from pathlib import Path
import logging
from logging.handlers import TimedRotatingFileHandler
from datetime import datetime

#
import toml
import pydash
from zoneinfo import ZoneInfo
from rich.logging import RichHandler

DEBUG = Path("DEBUG").exists() and Path("DEBUG").is_file()
# ================status_code================
F_SKIP = 2
F_EXIT = 1
F_OK = 0

# ================logger================
logging.getLogger("httpx").setLevel(logging.ERROR)
_BACKUP_COUNT = 14

LOG_DIR = Path("logs")
LOG_DIR.mkdir(0o755, parents=False, exist_ok=True)
FILE_HANDLER = TimedRotatingFileHandler(
    LOG_DIR / "software.log",
    "midnight",
    backupCount=_BACKUP_COUNT,
    encoding="utf-8",
)


def redirect_logger(logger_name):
    _FILE_FORMATTER_STR = "[%(asctime)s] %(levelname)s: %(message)s"
    FILE_HANDLER.setFormatter(logging.Formatter(_FILE_FORMATTER_STR))
    result = logging.getLogger(logger_name)
    result.setLevel(logging.DEBUG if DEBUG else logging.INFO)
    result.addHandler(FILE_HANDLER)
    rich_handler = RichHandler(show_path=False, show_time=False)
    result.addHandler(rich_handler)


# ================读取设置================
def preprocess_config():
    def set_if_empty(key, value):
        if pydash.get(CONFIG, key, "") == "":
            pydash.set_(CONFIG, key, value)

    set_if_empty("github.token", os.getenv("GITHUB_API_TOKEN", ""))
    set_if_empty("gitee.token", os.getenv("GITEE_API_TOKEN", ""))


CONFIG = toml.loads(Path("config.toml").read_text("utf-8"))
preprocess_config()

LOGGER = logging.getLogger("main")


# ================常规函数================
STD_TIME_FORMAT = "%Y-%m-%d %H:%M:%S"


def datetime_from_isoz(date_str: str):
    """
    :params: date_str = 2025-02-22T09:38:15Z , 2025-02-22T09:38:15+08:00
    """
    # 解析为带时区的 datetime 对象，fromisoformat 会自动处理时区信息
    aware_time = datetime.fromisoformat(date_str)
    # 转换为本地时区
    local_time = aware_time.astimezone(ZoneInfo("Asia/Shanghai"))
    # 移除时区信息，得到不带时区的 datetime
    return local_time.replace(tzinfo=None)


# ========计算version========
def _trans_pattern(rawstr: str):
    def _patterns_ver(key: str):
        pattern_first_part_map = {
            "ver": r"\d+",
            "ver_even": r"\d+[02468]|[2468]",
            "ver_odd": r"\d*[13579]",
        }
        return "".join((r"v?(?:", pattern_first_part_map[key], r")\.\d+(?:\.\d+){0,2}"))

    patterns = {
        "": r".+?",
        "ver": _patterns_ver("ver"),
        "ver_odd": _patterns_ver("ver_odd"),
        "ver_even": _patterns_ver("ver_even"),
        "num": r"\d+",
    }
    for var in set(patterns.keys()) & {"ver", "ver_odd", "ver_even", "num"}:
        rawstr = rawstr.replace("\\{%s\\}" % var, "({})".format(patterns[var]), 1).replace("\\{%s\\}" % var, "\\1")
    for var in set(patterns.keys()) & {""}:
        rawstr = rawstr.replace("\\{%s\\}" % var, "({})".format(patterns[var]))
    for var, pattern in patterns.items():
        rawstr = rawstr.replace("<%s>" % var, pattern)
    return rawstr + r"$"


def get_version_matcher(version_pattern: str):
    return re.compile(_trans_pattern(re.escape(version_pattern)), re.I)


def get_filling_pattern(version_pattern: str):
    # 镜像站专用函数，此时version_pattern不可能包括尖括号
    for var in {"", "ver", "ver_odd", "ver_even", "num"}:
        version_pattern = version_pattern.replace("{%s}" % var, "{0}")
    return version_pattern


def calc_version_from_filename(version_pattern: str, filename_str: str, version_tag: str = ""):
    if not version_pattern:
        return ""
    reobj = get_version_matcher(version_pattern)
    version_matched = reobj.match(filename_str)
    if not version_matched:
        return ""
    version = version_tag if len(version_matched.groups()) == 0 else version_matched.group(1)
    return ("" if version.lower().startswith("v") or not version else "v") + version
